package com.ld.poetry.utils;

import com.ld.poetry.config.MinioProperties;
import com.ld.poetry.utils.storage.StoreEnum;
import com.ld.poetry.utils.storage.StoreService;
import com.ld.poetry.vo.FileVO;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.UUID;

/**
 * minio工具类
 * @date: 2023-05-11 9:02
 * @description: TODO
 **/
@Component
@Slf4j
@ConditionalOnProperty(name = "minio.enable", havingValue = "true")
public class MinioUtil implements StoreService {

    @Autowired
    private MinioProperties minioProperties;

    @Autowired
    private MinioClient minioClient;

    @Override
    public void deleteFile(List<String> files) {

    }

    @Override
    public FileVO saveFile(FileVO fileVO) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        MultipartFile file = fileVO.getFile();

        String originalFileName = file.getOriginalFilename();
        String contentType = file.getContentType();

        String key = UUID.randomUUID().toString().replace("-", "");
        String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));

        String objectName = String.format("%s%s", key, suffix);

        log.info("==> 开始上传文件至 Minio, ObjectName: {}", objectName);
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(minioProperties.getBucketName())
                .object(objectName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(contentType)
                .build());

        String url = String.format("%s/%s/%s", minioProperties.getEndpoint(), minioProperties.getBucketName(), objectName);
        log.info("==> 上传文件至 Minio 成功，访问路径: {}", url);
        fileVO.setAbsolutePath(minioProperties.getEndpoint());
        fileVO.setVisitPath(url);
        return fileVO;
    }

    @Override
    public String getStoreName() {
        return StoreEnum.MINIO.getCode();
    }
}
